import React from 'react';
import PropTypes from 'prop-types';
import './index.scss';

/**
 *
 */
export default class RouterTab extends React.Component {
  static propTypes = {
    route: PropTypes.arrayOf(PropTypes.shape({
      path: PropTypes.string,
      text: PropTypes.string,
      component: PropTypes.node
    })).isRequired,
    defaultPath: PropTypes.string,
    onRouter: PropTypes.func,
    activeClassName: PropTypes.string,
    normalClassName: PropTypes.string
  }

  constructor(props) {
    super(props);
    this.state = {
      currentPath: props.defaultPath || props.route[0].path,
    };
  }

  onTabRouterClick = (e) => {
    const { onRouter, route } = this.props
    const { currentPath } = this.state;
    const path = e.currentTarget.dataset.path;
    if (currentPath !== path) {
      this.setState({
        currentPath: path
      }, () => {
        onRouter && onRouter(currentPath, path);
      });
    }
  }


  render() {
    const { route, activeClassName, normalClassName, className } = this.props;
    const { currentPath } = this.state;
    const uActiveClassName = activeClassName ? activeClassName : 'erayt-item-active';
    const uNormalClassName = normalClassName ? normalClassName : 'erayt-item-normal';
    const header = route.map(item => (
      <div className={`tab-header-item ${item.path === currentPath ? uActiveClassName : uNormalClassName}`} key={item.path} onClick={this.onTabRouterClick} data-path={item.path}>
        {item.text}
        { item.path === currentPath && <div className="tab-header-split" />}
      </div>
    ))
    return (
      <div className={`erayt-router-tab ${className ? className : ''}`}>
        <div className="erayt-router-tab-header bg-white">
          {header}
        </div>
        <div className="erayt-router-tab-content">
          {
            route.map((item) => {
              return (
                  <div key={item.path} className={`${item.path === currentPath ? 'active' : ''} erayt-router-content`}>
                    {item.component}
                  </div>
              );
            })
          }
        </div>
      </div>
    );
  }
}
